package pl.engine.ui
{
	import pl.engine.IIsoEngine;
	import pl.engine.camera.ICameraIsoParams;
	import pl.error.InternalError;

	import starling.core.Starling;
	import starling.events.KeyboardEvent;

	import com.greensock.TweenLite;

	import flash.ui.Keyboard;

	/**
	 * @author michalr
	 */
	public class KeysInput
	{
		private var isoEngine:IIsoEngine;
		private static var secureFunction:Function;

		public function KeysInput( isoEngine:IIsoEngine )
		{
			this.isoEngine = isoEngine;
			if (secureFunction == null)
			{
				throw new Error( InternalError.CREATION_ERROR );
			}
			Starling.current.stage.addEventListener( KeyboardEvent.KEY_DOWN, onKD );
			Starling.current.stage.addEventListener( KeyboardEvent.KEY_UP, onKUp );
		}

		public static function factory( isoEngine:IIsoEngine ):KeysInput
		{
			secureFunction = function():void
			{
			};
			return new KeysInput( isoEngine );
		}

		private function onKD( event:KeyboardEvent ):void
		{
			var camera:ICameraIsoParams = isoEngine.isoCamera;
			switch(event.keyCode)
			{
				case Keyboard.DOWN:
					TweenLite.to( camera, .1, {y:camera.y + 30, onUpdate:onTU} );
					break;
				case Keyboard.UP:
					TweenLite.to( camera, .1, {y:camera.y - 30, onUpdate:onTU} );
					break;
				case Keyboard.RIGHT:
					TweenLite.to( camera, .1, {x:camera.x + 30, onUpdate:onTU} );
					break;
				case Keyboard.LEFT:
					TweenLite.to( camera, .1, {x:camera.x - 30, onUpdate:onTU, onComplete:onTU} );
					break;
				case Keyboard.SPACE:
					UI.setCursorMode(UI.DRAG);
					break;
			}
		}

		private function onKUp( event:KeyboardEvent ):void
		{
			switch(event.keyCode)
			{
				case Keyboard.SPACE:
					UI.setCursorMode(UI.SELECT);
					break;
			}
		}

		private function onTU():void
		{
			isoEngine.isoCamera.x = Math.floor( isoEngine.isoCamera.x );
			isoEngine.isoCamera.y = Math.floor( isoEngine.isoCamera.y );
			isoEngine.updateWorld();
		}
	}
}
